import { Vue, Component, Prop, Emit } from 'vue-property-decorator';
import { Util } from '@ibizstudio/runtime';
import { ModelService } from '../service/model-service';
import { ModelData } from '../model-data';
import './model-clipboard-item.less';
import { ModelClipboardController } from '../controller/model-clipboard-controller';
import copy from 'copy-to-clipboard';


/**
 * 模型粘贴板项
 *
 * @export
 * @class ModelClipboardItem
 * @extends {Vue}
 */
@Component({})
export class ModelClipboardItem extends Vue {

    /**
     * 是否在编辑中
     *
     * @protected
     * @type {boolean}
     * @memberof ModelClipboardItem
     */
    protected isEdit: boolean = false;

    /**
     * 是否已销毁
     *
     * @protected
     * @type {boolean}
     * @memberof ModelClipboardItem
     */
    protected isDestroyed: boolean = false;

    /**
     * 是否正在加载模型
     *
     * @protected
     * @type {boolean}
     * @memberof ModelClipboardItem
     */
    protected isLoading: boolean = false;

    /**
     * 数据
     *
     * @protected
     * @type {ModelData}
     * @memberof ModelClipboardItem
     */
    @Prop()
    protected data!: ModelData;

    /**
     * 模型导出导入服务
     *
     * @protected
     * @type {ModelService}
     * @memberof ModelClipboardItem
     */
    protected service: ModelService = ModelService.getInstance();

    /**
     * 组件创建完毕
     *
     * @memberof ModelClipboardItem
     */
    created(): void {
        this.init();
    }

    /**
     * 组件销毁
     *
     * @memberof ModelClipboardItem
     */
    destroyed(): void {
        this.isDestroyed = true;
    }

    /**
     * 初始化
     *
     * @protected
     * @memberof ModelClipboardItem
     */
    protected async init(): Promise<void> {
        if (this.data && !this.data.isExport) {
            this.isLoading = true;
            for (let i: number = 0; i < this.data.items.length; i++) {
                const item: any = this.data.items[i];
                try {
                    const params: any = { srfdename: this.data.srfDeName, srfkey: item.srfkey };
                    if (this.data.srfParentData) {
                        params.srfparentdata = this.data.srfParentData;
                    }
                    const res: any = await this.service.loadModel(params);
                    if (res && res.status === 200) {
                        this.data.models.push(res.data);
                    }
                } catch (err: any) {
                    this.data.isError = true;
                    if (err && err.data) {
                        this.$Message.error({
                            content: `${this.data.title} 新建失败：${err.data.message}`,
                            duration: 3
                        });
                        this.data.errorInfo = err.data.message;
                    } else {
                        this.data.errorInfo = '模型导出发生未知错误!';
                    }
                    break;
                }
                if (this.isDestroyed) {
                    break;
                }
            }
            this.data.isExport = true;
            ModelClipboardController.getInstance().saveToStore();
            setTimeout(() => {
                this.isLoading = false;
            }, 300);
        }
    }

    /**
     * 删除当前项事件
     *
     * @returns {{ }}
     * @memberof ModelClipboardItem
     */
    @Emit('delete')
    delete(): any { }

    /**
     * 删除当前数据
     *
     * @memberof ModelClipboardItem
     */
    remove(): void {
        this.delete();
    }

    /**
     * 拷贝当前项
     *
     * @memberof ModelClipboardItem
     */
    copy(): void {
        const data: ModelData = Util.deepCopy(this.data);
        copy(JSON.stringify(data.models,null,2));
        this.$message({
          message: '已复制模型数据至剪贴板',
          showClose: true,
        });
    }

    /**
     * 打开或关闭编辑界面
     *
     * @protected
     * @param {boolean} [bool=!this.isEdit]
     * @memberof ModelClipboardItem
     */
    protected editChange(bool: boolean = !this.isEdit): void {
        this.isEdit = bool;
    }

    /**
     * 绘制项编辑界面
     *
     * @protected
     * @returns {*}
     * @memberof ModelClipboardItem
     */
    protected renderEdit(): any {
        return <drawer title={this.data.title} class-name="model-clipboard-item-edit-drawer" mask-closable={false} placement="right" width="800" v-model={this.isEdit}>
            <app-code-editor key="code-content-ftl" codetype="json" height="100%" />
        </drawer>;
    }

    /**
     * 绘制项
     *
     * @returns {*}
     * @memberof ModelClipboardItem
     */
    render(): any {
        let type: string = 'info';
        if (this.data.isExport) {
            type = 'success';
        } else if (this.data.isError) {
            type = 'danger';
        } else if (this.isLoading) {
            type = 'warning';
        }
        return <el-timeline-item timestamp={this.data.createdDate} type={type} placement="top">
            <el-card class="model-clipboard-item" shadow="hover">
                <div class="model-clipboard-item-content">
                    <div class="title">
                        <input v-model={this.data.title} on-blur={() => ModelClipboardController.getInstance().saveToStore()} />
                    </div>
                    <div class="info-warp">
                        <div class="info-item">
                            共{this.data.items.length}条模型数据
                    </div>
                    </div>
                    <div class="actions">
                        <button-group>
                            <i-button title="拷贝" type="text" ghost icon="ios-copy" on-click={() => this.copy()} disabled={this.isLoading} />
                            {/* <i-button title="编辑" type="text" ghost icon="ios-create" on-click={() => this.editChange(true)}/> */}
                            <i-button title="删除" type="text" ghost icon="ios-trash" on-click={() => this.remove()} />
                        </button-group>
                    </div>
                    {this.isEdit ? this.renderEdit() : null}
                </div>
                {this.isLoading ? <div class={{ 'model-item-loading-warp': true }}>
                    <div class={{ 'model-item-loading-inner': true }} style={{ 'width': (this.data.models.length / this.data.items.length) * 100 + '%' }}>
                        <div class="label">
                            {this.data.models.length}/{this.data.items.length}
                        </div>
                    </div>
                </div> : null}
            </el-card>
        </el-timeline-item>;
    }

}